package com.wtwd.campus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.entity.Grade;
import com.wtwd.campus.entity.School;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.model.vo.GradeVO;
import com.wtwd.campus.model.vo.PageDataVO;
import com.wtwd.campus.model.vo.ResultVO;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.AuditLogUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zdl
 * @since 2021-06-30
 */
@Api(tags = "年级管理")
@RestController
@RequestMapping("/grade")
public class GradeController {
    @Resource
    private GradeService gradeService;

    @Resource
    private ClassService classService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SchoolService schoolService;
    @Autowired
    private LogService logService;


    @ApiOperation(value = "查询年级分页数据", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "schoolId", value = "学校ID", dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public ResultVO<PageDataVO<GradeVO>> queryPage(@RequestParam(defaultValue = "1") Integer pageNo
            , @RequestParam(defaultValue = "10") Integer pageSize, Integer schoolId) {
        Page<GradeVO> page = new Page<>(pageNo, pageSize);
        SysUser user = sysUserService.getCurrentLoginUser();
        List<Integer> schoolIds;
        if (schoolId == null) {
            List<School> schools = schoolService.getSchoolByOrgCode(user.getOrgCode());
            schoolIds = schools.stream().map(School::getId).collect(Collectors.toList());
        } else {
            schoolIds = new ArrayList<>();
            schoolIds.add(schoolId);
        }
        IPage<GradeVO> datPage = gradeService.queryPage(page, schoolIds);
        List<GradeVO> records = datPage.getRecords();
        if (records.size() == 0) {
            return ResultVO.ok(datPage);
        }
        // TODO 获取各年级下班级个数
        List<Integer> gradeIds = datPage.getRecords().stream().map(GradeVO::getGradeId).collect(Collectors.toList());
        Map<Integer, Integer> classNum = classService.countClassByGradeIds(gradeIds);
        if (classNum != null && classNum.size() != 0) {
            records.forEach(item -> {
                item.setClassCount(classNum.get(item.getGradeId()));
            });
        }
        return ResultVO.ok(datPage);
    }

    @ApiOperation("添加年级信息")
    @DynamicParameters(name = "addGradeModel", properties = {
            @DynamicParameter(name = "schoolId", value = "学校ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "gradeNames", value = "年级名称", dataTypeClass = String.class, required = true, example = "1,2,3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "参数错误")})
    @PostMapping("/gradeInfo")
    @AuditLog(operationType = "添加年级", operationContent = "", orgCode = "")
    public ResultVO add(@RequestBody JSONObject addgradeModel) {
        Grade grade = JSONObject.toJavaObject(addgradeModel, Grade.class);
        ResultVO resultVO = gradeService.createGradeBatch(grade, addgradeModel.getString("gradeNames"));
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = GradeController.class.getMethod("add", JSONObject.class);
                //获取操作的组织的code
                String orgCode = logService.getOrgCodeBySchoolId(grade.getSchoolId());
                String operationContent ="";
                String name=addgradeModel.getString("gradeNames");
                if(name.contains(",")){
                    String[] split = name.split(",");
                    operationContent = "新增".concat(String.valueOf(split.length)).concat("个年级");
                }else{
                    operationContent = "新增年级：".concat(name);
                }
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }


    @ApiOperation("删除年级信息")
    @ApiImplicitParam(name = "id", value = "年级id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @ApiResponses({@ApiResponse(code = 1013, message = "该年级下存在班级")})
    @DeleteMapping("/gradeInfo/{id}")
    @AuditLog(operationType = "删除年级", operationContent = "", orgCode = "")
    public ResultVO delete(@PathVariable Integer id) {
        //根据年级id获取学校信息
        Map<String, Object> map = logService.getSchoolAndGradeByGradeId(id);
        ResultVO resultVO = gradeService.deleteGradeById(id);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = GradeController.class.getMethod("delete", Integer.class);
                //获取操作的组织的code
                String orgCode = (String) map.get("org_code");
                String gradeName = (String) map.get("grade_name");
                String operationContent = "删除年级：".concat(gradeName);
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

}

